import { Button, Form, Input, Select, TreeSelect } from "antd"
import React, { useEffect } from "react";
import { WidgetConfig } from "../../types/FormInterface";



interface FormComponentProps {
    widgets: WidgetConfig[],
    data: any[],
    changeData: Function,
    OpenModal: Function
}

const FormItem: React.FC<WidgetConfig> = ({ type, title, dataIndex, defaultData }) => {
    switch (type) {
        case 'select':
            return (
                <Form.Item label={title} name={dataIndex} rules={[{ required: true, message: 'Please select an option!' }]}>
                    <Select placeholder="Select an option" >
                    </Select>
                </Form.Item>
            );
        case 'input':
            return (
                <Form.Item label={title} name={dataIndex} rules={[{ required: true, message: 'Please input something!' }]}>
                    <Input />
                </Form.Item>
            );
        case 'mutipleSelect':
            return (
                <Form.Item label={title} name={dataIndex} rules={[{ required: true, message: 'Please select an option!' }]}>
                    <Select placeholder="Select an option" mode="multiple">
                    </Select>
                </Form.Item>
            );

        case 'treeSelect':
            return (
                <Form.Item label={title} name={dataIndex} rules={[{ required: true, message: 'Please select an option!' }]}>
                    <TreeSelect treeData={defaultData} treeCheckable='true' showCheckedStrategy='SHOW_PARENT' />
                </Form.Item>
            )
        default:
            return null;
    }
};

const FormComponent: React.FC<FormComponentProps> = ({ widgets, data, changeData, OpenModal }) => {
    console.log(widgets, data, 66)
    const [form] = Form.useForm();
    const handleConfirm = () => {
        OpenModal()
        changeData(form.getFieldsValue())
    }


    useEffect(() => {
        form.setFieldsValue(data)
        console.log(form.getFieldsValue())
    }, [])


    return (
        <>
            <Form className="form" form={form} >
                {widgets.map(widget => (
                    <FormItem {...widget} key={widget.key} />
                ))}
            </Form>
            <Button type="primary" onClick={() => handleConfirm()}>确定</Button>
        </>
    );
};

export default FormComponent